package com.simple.mq.core.network.server;

import com.alibaba.fastjson.JSON;
import com.simple.mq.common.config.SimpleMqServerConfig;
import com.simple.mq.core.config.DefaultConsumer;
import com.simple.mq.core.network.core.BasicMaps;
import com.simple.mq.core.network.initializer.SimpleMqServerInitializer;
import com.simple.mq.common.util.BannerUtil;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.Channel;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import lombok.extern.slf4j.Slf4j;

import java.util.Objects;

/**
 * 项目: simple-mq
 *
 * 功能描述: mq的启动器
 *
 * @author: WuChengXing
 *
 * @create: 2023-09-04 14:05
 **/
@Slf4j(topic = "SimpleMqServer")
public class SimpleMqServer implements Runnable {

    private final SimpleMqServerConfig simpleMqServerConfig;

    public SimpleMqServer(SimpleMqServerConfig simpleMqServerConfig) {
        this.simpleMqServerConfig = simpleMqServerConfig;
    }

    @Override
    public void run() {
        EventLoopGroup mainGroup = new NioEventLoopGroup();
        EventLoopGroup subGroup = new NioEventLoopGroup();
        ServerBootstrap server = new ServerBootstrap();
        server.group(mainGroup, subGroup)
                .channel(NioServerSocketChannel.class)
                .childHandler(new SimpleMqServerInitializer());
        try {
            BannerUtil.loadBanner("banner.txt");
            // 初始化配置
            Class.forName("com.simple.mq.core.config.SimpleMqConfig");

            Channel channel = server.bind(Objects.isNull(simpleMqServerConfig.getPort()) ? 18888 : simpleMqServerConfig.getPort()).sync().channel();
            log.info("Server starts successfully!");
            // 初始化默认消费者
            new Thread(new DefaultConsumer()).start();
            Thread.sleep(3000);
            log.info("目前注册的消费着：【{}】", JSON.toJSONString(BasicMaps.queueConsumerMap.keySet()));
            channel.closeFuture().sync();
        } catch (Exception e) {
            log.error("server error", e);
            e.printStackTrace();
        } finally {
            mainGroup.shutdownGracefully();
            subGroup.shutdownGracefully();
        }
    }
}
